import 'package:state_beacon/state_beacon.dart';
import '../models/chat_message_model.dart';
import 'user_state.dart';

/// 私人对话状态管理器
class PrivateConversationState {
  // 静态状态变量
  static List<ChatMessageModel> _conversationMessages = [];
  static Map<String, int> _unreadCountMap = {}; // 用户未读消息数量映射

  // State Beacon 实例
  static final conversationMessagesBeacon =
      Beacon.writable<List<ChatMessageModel>>(_conversationMessages);
  static final unreadCountMapBeacon = Beacon.writable<Map<String, int>>(
    _unreadCountMap,
  );

  /// 初始化默认对话数据
  static void _initializeDefaultConversations() {
    if (_conversationMessages.isNotEmpty) return; // 避免重复初始化

    // 初始化默认未读消息数量
    _unreadCountMap = {
      'user_001':
          5, // user_001用户有5条未读消息（来自user_002:2, user_004:1, user_006:1, user_003:1）
      'user_002': 0, // user_002用户没有未读消息
      'user_003': 0, // user_003用户没有未读消息
      'user_004': 0, // user_004用户没有未读消息
      'user_005': 0, // user_005用户没有未读消息
      'user_006': 0, // user_006用户没有未读消息
    };

    // 初始化默认对话消息数据 - 围绕user_001用户创建
    _conversationMessages = [
      // user_001与user_002的对话
      ChatMessageModel(
        messageId: 'msg_001',
        senderId: 'user_002',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'Hey LemurFan! I just spotted a group of ring-tailed lemurs near the baobab tree. They were doing their morning sunbathing ritual!',
        sendTime: DateTime.now().subtract(const Duration(hours: 2)),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_002',
        senderId: 'user_001',
        receiverId: 'user_002',
        messageType: ChatMessageType.text,
        content:
            'That\'s amazing! Ring-tailed lemurs are such social creatures. Did you notice their scent marking behavior?',
        sendTime: DateTime.now().subtract(
          const Duration(hours: 1, minutes: 45),
        ),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_003',
        senderId: 'user_002',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'Yes! They were marking their territory on the tree branches. I managed to capture some footage of their communication calls too.',
        sendTime: DateTime.now().subtract(
          const Duration(hours: 1, minutes: 30),
        ),
        isRead: false, // 未读消息
      ),

      // user_001与user_003的对话
      ChatMessageModel(
        messageId: 'msg_004',
        senderId: 'user_001',
        receiverId: 'user_003',
        messageType: ChatMessageType.text,
        content:
            'BaobabX, I heard you discovered a new baobab tree location! How old do you think it is?',
        sendTime: DateTime.now().subtract(const Duration(hours: 4)),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_005',
        senderId: 'user_003',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'Based on the trunk circumference, I estimate it\'s over 800 years old! The local community has been using it as a meeting place for generations.',
        sendTime: DateTime.now().subtract(
          const Duration(hours: 3, minutes: 30),
        ),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_006',
        senderId: 'user_001',
        receiverId: 'user_003',
        messageType: ChatMessageType.text,
        content:
            'Incredible! These ancient trees are truly the guardians of Madagascar\'s history. We should document this for conservation purposes.',
        sendTime: DateTime.now().subtract(const Duration(hours: 3)),
        isRead: false, // 未读消息
      ),
      ChatMessageModel(
        messageId: 'msg_007',
        senderId: 'user_003',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'Absolutely! I\'ll share the GPS coordinates and photos with the conservation team. These trees need protection.',
        sendTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        isRead: false, // 未读消息
      ),

      // user_001与user_003的对话 - 包含拨打失败消息
      ChatMessageModel(
        messageId: 'msg_008',
        senderId: 'user_001',
        receiverId: 'user_003',
        messageType: ChatMessageType.text,
        content:
            'Chameleo, I need your expertise on chameleon behavior. Are you available for a quick consultation?',
        sendTime: DateTime.now().subtract(const Duration(hours: 6)),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_009',
        senderId: 'user_003',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'Of course! I\'m currently in the field observing a panther chameleon color change. What specific behavior are you curious about?',
        sendTime: DateTime.now().subtract(
          const Duration(hours: 5, minutes: 30),
        ),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_010',
        senderId: 'user_001',
        receiverId: 'user_003',
        messageType: ChatMessageType.callFailed,
        content: 'Call failed - Network connection lost',
        sendTime: DateTime.now().subtract(const Duration(hours: 5)),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_011',
        senderId: 'user_003',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'Sorry about the connection issue! I\'m back online now. The chameleon I was observing just completed an amazing color transformation from green to deep red.',
        sendTime: DateTime.now().subtract(
          const Duration(hours: 4, minutes: 45),
        ),
        isRead: true,
      ),

      // user_001与user_004的对话
      ChatMessageModel(
        messageId: 'msg_012',
        senderId: 'user_004',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'LemurFan, I captured some incredible footage of a fossa hunting behavior today. These apex predators are so elusive!',
        sendTime: DateTime.now().subtract(const Duration(days: 1)),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_013',
        senderId: 'user_001',
        receiverId: 'user_004',
        messageType: ChatMessageType.text,
        content:
            'FossaPro, that\'s fantastic! Fossas are such fascinating creatures. How close were you able to get without disturbing them?',
        sendTime: DateTime.now().subtract(const Duration(days: 1, minutes: 30)),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_014',
        senderId: 'user_004',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'I maintained a safe distance of about 50 meters using a telephoto lens. The fossa was completely unaware of my presence, which allowed for natural behavior observation.',
        sendTime: DateTime.now().subtract(const Duration(days: 1, minutes: 15)),
        isRead: false, // 未读消息
      ),

      // user_001与user_005的对话 - 包含拨打失败消息
      ChatMessageModel(
        messageId: 'msg_015',
        senderId: 'user_001',
        receiverId: 'user_005',
        messageType: ChatMessageType.text,
        content:
            'GeckoEye, I\'m planning a night safari next week. Any tips for spotting nocturnal geckos?',
        sendTime: DateTime.now().subtract(const Duration(days: 2)),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_016',
        senderId: 'user_005',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'Great timing! The best spots are near the limestone formations. Bring a red light torch - geckos are less sensitive to red light.',
        sendTime: DateTime.now().subtract(const Duration(days: 2, hours: 2)),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_017',
        senderId: 'user_001',
        receiverId: 'user_005',
        messageType: ChatMessageType.callFailed,
        content: 'Call failed - User unavailable',
        sendTime: DateTime.now().subtract(const Duration(days: 1, hours: 8)),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_018',
        senderId: 'user_005',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'Sorry I missed your call! I was deep in the forest tracking a rare leaf-tailed gecko. Found three different species last night!',
        sendTime: DateTime.now().subtract(const Duration(days: 1, hours: 6)),
        isRead: true,
      ),

      // user_001与user_006的对话
      ChatMessageModel(
        messageId: 'msg_019',
        senderId: 'user_006',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'TenrecX here! I discovered a new tenrec nesting site in the spiny forest. These little creatures are so well camouflaged!',
        sendTime: DateTime.now().subtract(const Duration(days: 3)),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_020',
        senderId: 'user_001',
        receiverId: 'user_006',
        messageType: ChatMessageType.text,
        content:
            'That\'s incredible! Tenrecs are such unique mammals. Did you observe any interesting behaviors?',
        sendTime: DateTime.now().subtract(const Duration(days: 3, hours: 1)),
        isRead: true,
      ),
      ChatMessageModel(
        messageId: 'msg_021',
        senderId: 'user_006',
        receiverId: 'user_001',
        messageType: ChatMessageType.text,
        content:
            'Yes! I saw a mother tenrec teaching her young how to forage for insects. Their quills are fascinating - they can vibrate them to create sound!',
        sendTime: DateTime.now().subtract(const Duration(days: 3, hours: 30)),
        isRead: false, // 未读消息
      ),
    ];

    // 更新 Beacon 状态
    conversationMessagesBeacon.value = List.from(_conversationMessages);
    unreadCountMapBeacon.value = Map.from(_unreadCountMap);
  }

  /// 初始化状态
  static void initialize() {
    _initializeDefaultConversations();
  }

  /// 获取两个用户之间的对话消息
  static List<ChatMessageModel> getConversationBetweenUsers(
    String userId1,
    String userId2,
  ) {
    _initializeDefaultConversations();
    return _conversationMessages
        .where(
          (message) =>
              (message.senderId == userId1 && message.receiverId == userId2) ||
              (message.senderId == userId2 && message.receiverId == userId1),
        )
        .toList()
      ..sort((a, b) => a.sendTime.compareTo(b.sendTime));
  }

  /// 发送文本消息
  static void sendTextMessage({
    required String senderId,
    required String receiverId,
    required String content,
  }) {
    _initializeDefaultConversations();
    final newMessage = ChatMessageModel(
      messageId: 'msg_${DateTime.now().millisecondsSinceEpoch}',
      senderId: senderId,
      receiverId: receiverId,
      messageType: ChatMessageType.text,
      content: content,
      sendTime: DateTime.now(),
      isRead: false,
    );

    _conversationMessages.add(newMessage);
    conversationMessagesBeacon.value = List.from(_conversationMessages);

    // 更新未读消息数量
    _updateUnreadCount(receiverId, 1);
  }

  /// 发送拨打失败消息
  static void sendCallFailedMessage({
    required String senderId,
    required String receiverId,
    required String failureReason,
  }) {
    _initializeDefaultConversations();
    final newMessage = ChatMessageModel(
      messageId: 'msg_${DateTime.now().millisecondsSinceEpoch}',
      senderId: senderId,
      receiverId: receiverId,
      messageType: ChatMessageType.callFailed,
      content: 'Call failed - $failureReason',
      sendTime: DateTime.now(),
      isRead: false,
    );

    _conversationMessages.add(newMessage);
    conversationMessagesBeacon.value = List.from(_conversationMessages);

    // 更新未读消息数量
    _updateUnreadCount(receiverId, 1);
  }

  /// 标记消息为已读
  static void markMessageAsRead(String messageId) {
    _initializeDefaultConversations();
    final messageIndex = _conversationMessages.indexWhere(
      (msg) => msg.messageId == messageId,
    );
    if (messageIndex == -1) return;

    final message = _conversationMessages[messageIndex];
    if (!message.isRead) {
      _conversationMessages[messageIndex] = message.copyWith(isRead: true);
      conversationMessagesBeacon.value = List.from(_conversationMessages);

      // 更新未读消息数量
      _updateUnreadCount(message.receiverId, -1);
    }
  }

  /// 标记与特定用户的所有消息为已读
  static void markAllMessagesAsRead(String currentUserId, String otherUserId) {
    _initializeDefaultConversations();
    bool hasChanges = false;

    for (int i = 0; i < _conversationMessages.length; i++) {
      final message = _conversationMessages[i];
      if (message.senderId == otherUserId &&
          message.receiverId == currentUserId &&
          !message.isRead) {
        _conversationMessages[i] = message.copyWith(isRead: true);
        hasChanges = true;
      }
    }

    if (hasChanges) {
      conversationMessagesBeacon.value = List.from(_conversationMessages);
      _updateUnreadCount(currentUserId, 0); // 重置未读数量
    }
  }

  /// 更新未读消息数量
  static void _updateUnreadCount(String userId, int change) {
    if (!_unreadCountMap.containsKey(userId)) {
      _unreadCountMap[userId] = 0;
    }

    if (change == 0) {
      // 重置未读数量
      _unreadCountMap[userId] = 0;
    } else {
      // 增加或减少未读数量
      _unreadCountMap[userId] =
          (_unreadCountMap[userId]! + change).clamp(0, double.infinity).toInt();
    }

    unreadCountMapBeacon.value = Map.from(_unreadCountMap);
  }

  /// 获取用户的未读消息数量
  static int getUnreadCount(String userId) {
    _initializeDefaultConversations();
    return _unreadCountMap[userId] ?? 0;
  }

  /// 获取用户的所有对话伙伴列表
  static List<String> getConversationPartners(String userId) {
    _initializeDefaultConversations();
    final Set<String> partners = {};

    for (final message in _conversationMessages) {
      if (message.senderId == userId) {
        partners.add(message.receiverId);
      } else if (message.receiverId == userId) {
        partners.add(message.senderId);
      }
    }

    return partners.toList();
  }

  /// 获取与特定用户的最后一条消息
  static ChatMessageModel? getLastMessageWithUser(
    String userId1,
    String userId2,
  ) {
    _initializeDefaultConversations();
    final conversation = getConversationBetweenUsers(userId1, userId2);
    return conversation.isNotEmpty ? conversation.last : null;
  }

  /// 删除消息
  static bool removeMessage(String messageId) {
    _initializeDefaultConversations();
    final messageIndex = _conversationMessages.indexWhere(
      (msg) => msg.messageId == messageId,
    );
    if (messageIndex == -1) return false;

    final message = _conversationMessages[messageIndex];
    _conversationMessages.removeAt(messageIndex);
    conversationMessagesBeacon.value = List.from(_conversationMessages);

    // 如果删除的是未读消息，更新未读数量
    if (!message.isRead) {
      _updateUnreadCount(message.receiverId, -1);
    }

    return true;
  }

  /// 根据用户ID获取用户信息（用于显示用户名和头像）
  static Map<String, String>? getUserInfo(String userId) {
    final user = UserState.queryUserById(userId);
    if (user != null) {
      return {'userName': user.userName, 'userAvatar': user.avatar};
    }
    return null;
  }

  /// 删除对话（举报后删除）
  static void deleteConversation(String currentUserId, String partnerId) {
    // 删除所有相关消息
    _conversationMessages.removeWhere(
      (message) =>
          (message.senderId == currentUserId &&
              message.receiverId == partnerId) ||
          (message.senderId == partnerId &&
              message.receiverId == currentUserId),
    );

    // 清除未读消息计数
    _unreadCountMap.remove(partnerId);

    // 更新状态
    conversationMessagesBeacon.value = List.from(_conversationMessages);
    unreadCountMapBeacon.value = Map.from(_unreadCountMap);
  }

  // Getters for reactive state
  static ReadableBeacon<List<ChatMessageModel>> get conversationMessages =>
      conversationMessagesBeacon;
  static ReadableBeacon<Map<String, int>> get unreadCountMap =>
      unreadCountMapBeacon;
}
